<?php

namespace App\Mobile\Controllers;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use DB;
use Auth;
use Validator;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Redis;
use App\User;
use App\LotteryLog;

class LotteryController extends Controller
{
	protected $config = [
	    'app_id' => 'wx555be570d21859aa',
	    'secret' => 'f92678be7687d1e1b1471ca9c066f242',

	    // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
	    'response_type' => 'array',

	    'log' => [
	        'level' => 'debug',
	        'file' => __DIR__.'/wechat.log',
	    ],
	    /**
	     * OAuth 配置
	     *
	     * scopes：公众平台（snsapi_userinfo / snsapi_base），开放平台：snsapi_login
	     * callback：OAuth授权完成后的回调页地址
	     */
	    'oauth' => [
	        'scopes'   => ['snsapi_userinfo'],
	        'callback' => '/mobile/callback',
	    ],
	];

	/**
	 * [index 抽奖首页]
	 * @param  User   $user [description]
	 * @return [type]       [description]
	 */
	public function index(User $user)
	{
        $app = new Application($this->config);
        $js = $app->js;
        $url = 'http://user.leyougame.cc/mobile/draw_lottery';
		$draw_arr = $user->completeTaskUser();
		$draw_num = ($draw_arr['draw_number'] > 5) ? 5 : $draw_arr['draw_number'];//获取可以抽奖的次数
		$next_user = $draw_arr['next_user'] ? $draw_arr['next_user']->userid: 0;
		$today_num = $user->todayDrawNum();//获取今日抽奖次数
		$today_draw_num = ($draw_num - $today_num < 0) ? 0 : $draw_num - $today_num;
		$my_invite_users = User::where(['invite_id' => $user->userid])->get();//我邀请的玩家
		$lottery_logs = LotteryLog::where(['draw_id' => $user->userid])->get();//我的中奖记录
		$lucky_logs = Lotterylog::orderBy('created_at', 'DESC')->limit(50)->get();
		/*今日没有抽奖次数，判断是否赠送抽奖*/
		if ($today_draw_num == 0) {
			$key = 'lottery_set_' . date('Y-m-d', time());//redis set key
			if (Redis::exists($key)) {//key 是否存在
				if (!Redis::sismember($key, $user->userid)) {//判断set中是否有userid
					$today_draw_num += 1;//赠送本日抽奖次数1次
				}
			} else {
				$today_draw_num += 1;//赠送本日抽奖次数1次
			}
		}	

		return view('mobile.lottery.index', compact('today_draw_num', 'my_invite_users', 'lottery_logs', 'user', 'lucky_logs', 'next_user', 'js', 'url'));
	}

	/**
	 * [drawLottery 抽奖]
	 * @return [type] [description]
	 */
	public function drawLottery(User $user, Request $request)
	{
		$draw_arr = $user->completeTaskUser();
		$draw_num = ($draw_arr['draw_number'] > 5) ? 5 : $draw_arr['draw_number'];//获取可以抽奖的次数
		$today_num = $user->todayDrawNum();//获取今日抽奖次数
		$today_draw_num = ($draw_num - $today_num < 0) ? 0 : $draw_num - $today_num;
		if ($today_draw_num == 0) {
			$key = 'lottery_set_' . date('Y-m-d', time());//redis set key
			if (Redis::exists($key)) {//key 是否存在
				if (!Redis::sismember($key, $user->userid)) {//判断set中是否有userid
					Redis::sadd($key, $user->userid);//向set中加入userid
				} else {
					return ['flag' => false, 'msg' => '今日抽奖次数已用尽'];
				}
			} else {
				Redis::sadd($key, $user->userid);//向set中加入userid
			}
		}	
		$prize_arr = array( 
		    '0' => array('id'=>1, 'prize'=>'话费1元','v'=>50), 
		    '1' => array('id'=>2, 'prize'=>'银票3张','v'=>20), 
		    '2' => array('id'=>3, 'prize'=>'话费3元','v'=>20), 
		    '3' => array('id'=>4, 'prize'=>'银票5张','v'=>5), 
		    '4' => array('id'=>5, 'prize'=>'话费5元','v'=>5), 
		    '5' => array('id'=>6, 'prize'=>'话费10元','v'=>0), 
		    '6' => array('id'=>7, 'prize'=>'话费20元','v'=>0), 
		    '7' => array('id'=>8, 'prize'=>'话费50元','v'=>0), 
		    '8' => array('id'=>9, 'prize'=>'乐游兑换券10张','v'=>0), 
		    '9' => array('id'=>10, 'prize'=>'话费100元','v'=>0), 
		); 
		foreach ($prize_arr as $key => $val) { 
		    $arr[$val['id']] = $val['v']; 
		} 
		$pid = $this->get_rand($arr);//中奖id

		$this->recordLottery($user, $pid, $request->input('next_user'));//记录中奖信息
		$this->sendMessage($user, $pid);//微信消息提醒
		$rotate_id = 1;
		switch ($pid) {
			case 1: 
				$rotate_id = 8;
				break;
			case 2:
				$rotate_id = 9;
				break;	
			case 3:
				$rotate_id = 10;
				break;	
			case 4:
				$rotate_id = 1;
				break;
			case 5:
				$rotate_id = 2;
				break;
			case 6:
				$rotate_id = 4;
				break;
			case 7:
				$rotate_id = 6;
				break;
			case 8:
				$rotate_id = 5;
				break;
			case 9:
				$rotate_id = 7;
				break;
			case 10:
				$rotate_id = 3;
				break;
		}
		return ['flag' => true, 'data' => $rotate_id];
	}

	/**
	 * [get_rand 抽奖]
	 * @param  [type] $proArr [description]
	 * @return [type]         [description]
	 */
	public function get_rand($proArr) { 
	    $result = ''; 

	    //概率数组的总概率精度
	    $proSum = array_sum($proArr); 

	    //概率数组循环
	    foreach ($proArr as $key => $proCur) { 
	        $randNum = mt_rand(1, $proSum); 
	        if ($randNum <= $proCur) { 
	            $result = $key; 
	            break; 
	        } else { 
	            $proSum -= $proCur; 
	        } 
	    } 
	    unset ($proArr); 

	    return $result; 
	}

	/**
	 * [recordLottery description]
	 * @return [type] [description]
	 */
	public function recordLottery($user, $pid, $next_user)
	{
		$price_arr = [
				1 => '话费1元', 
				2 => '银票3张',
				3 => '话费3元',
				4 => '银票5张',
				5 => '话费5元',
				6 => '话费10元',
				7 => '话费20元',
				8 => '话费50元',
				9 => '乐游兑换券10张',
				10 => '话费100元'
		    ];
		$log = new Lotterylog;
		$log->draw_id = $user->userid;
		$log->draw_name = base64_decode($user->name);
		$log->draw_avatar = $user->headimg;
		$log->price_id = $pid;
		$log->price_name = $price_arr[$pid];
		$log->user_id = $next_user;
		$log->save();
		$this->sendLottery($user, $pid);
		return;
	}

	/**
	 * [sendLottery 发奖]
	 * @return [type] [description]
	 */
	public function sendLottery($user, $pid)
	{
		if (in_array($pid, [1,3,5,6,7,8,10])) {//话费
			$money = 0;
			switch ($pid) {
				case 1:
					$money = 1;
					break;
				case 3:
					$money = 3;
					break;
				case 5:
					$money = 5;
					break;
				case 6:
					$money = 10;
					break;
				case 7:
					$money = 20;
					break;
				case 8:
					$money = 50;
					break;
				case 10:
					$money = 100;
					break;		
			}
			$user->money += $money;
			$user->save();
		} else if (in_array($pid, [2,4])) {//银票
			$gems = 0;
			switch ($pid) {
				case 2:
					$gems = 3;
					break;
				case 4:
					$gems = 5;
					break;
			}
			$user->gems += $gems;
			$user->save();
		} else {//兑换券

		}

		return;
	}

	/**
	 * [sendMessage 微信消息提醒]
	 * @param  [type] $user [description]
	 * @param  [type] $pid  [description]
	 * @return [type]       [description]
	 */
	public function sendMessage($user, $pid)
	{
		$price_arr = [
			1 => '话费1元', 
			2 => '银票3张',
			3 => '话费3元',
			4 => '银票5张',
			5 => '话费5元',
			6 => '话费10元',
			7 => '话费20元',
			8 => '话费50元',
			9 => '乐游兑换券10张',
			10 => '话费100元'
	    ];
	    $message = $price_arr[$pid];
		$agent = $user->agent();
		if ($agent) {
		    $app = new Application($this->config);
		    $userService = $app->user;
		    $suser = $userService->get($agent->open_id);
		    $subscribe = $suser->subscribe;
		    if ($subscribe != 0) {
		        $notice = $app->notice;
		        $openId = $agent->open_id;
		        $templateId = 'X6CfcQymad5q1sP2ea_XNJtz5wTwwaOuiyseBOgxBz0';
		        $url = "";
		        $data = array(
		            "first" => "恭喜您中奖了，奖品已发送至您的游戏账号",
		            "keyword1" => "幸运大转盘",
		            "keyword2" => $message,
		            "keyword3" => date("Y-m-d H:i", time()),
		            "remark" => "祝您游戏愉快!",
		        );
		        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($openId)->send();
		    }  
		}
		return;
	}



}	